package com.qujia.station.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author GW
 * @Version 1.0
 * @Description
 * @since 2020/12/12 15:05
 */
@Service
public class Sha256SignCreator  {
    public static String createSign(String message, String signKey) {
        try {
            // 创建加密对象
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256".intern());
            // 传入要加密的字符串,按指定的字符集将字符串转换为字节流
            messageDigest.update((message + "&key=" + signKey).getBytes("UTF-8".intern()));
            byte byteBuffer[] = messageDigest.digest();
            // 將 byte转换为16进制string
            StringBuffer strHexString = new StringBuffer();
            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            return strHexString.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public String encode(JSONObject signParams, String key) {
        JSONObject jsonClone = (JSONObject) signParams.clone();
        jsonClone.remove("sign");
        String plainText = this.getJsonOrderString(jsonClone);
        return DigestUtils.sha256Hex(plainText.concat("&key=").concat(key));
    }

    private String getJsonOrderString(JSONObject json) {
        List<String> list = new ArrayList();
        json.forEach((k, v) -> {
            if (v instanceof JSONObject) {
                JSONObject jsonV = (JSONObject)v;
                list.add(k + '=' + this.getJsonOrderString(jsonV));
            } else {
                list.add(k + '=' + v);
            }

        });
        list.sort(String::compareTo);
        return StringUtils.join(list, '&');
    }
}
